package nettyTest.netty3Test.decodetest.lengthField;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;

import java.nio.ByteOrder;

/**
 * @author      : yang.xp
 * @date        : 2021/8/26 15:52
 * @description : LengthFieldBasedFrameDecoder 使用了这个解码器
 */
public class LengthFieldDecodeTestServer {

    public static void main(String[] args) {
        ServerBootstrap serverBootstrap = new ServerBootstrap();
        NioEventLoopGroup bossGroup = new NioEventLoopGroup();
        NioEventLoopGroup workGroup = new NioEventLoopGroup(4);
        serverBootstrap.group(bossGroup, workGroup).handler(new LoggingHandler(LogLevel.DEBUG))
                .channel(NioServerSocketChannel.class)
                .childOption(ChannelOption.TCP_NODELAY, true)
                .childHandler(new ChannelInitializer<Channel>() {
                    @Override
                    protected void initChannel(Channel ch) throws Exception {
                        ChannelPipeline channelPipeline = ch.pipeline();
                        channelPipeline.addLast(new LengthFieldBasedFrameDecoder(ByteOrder.BIG_ENDIAN, 1024,
                                0, 2, 0, 0, true));
                        channelPipeline.addLast(new ChannelInboundHandlerAdapter() {
                            @Override
                            public void channelRead(ChannelHandlerContext ctx, Object msg) {
                                ByteBuf str = (ByteBuf) msg;
                                short i = str.readShort();
                                short j = str.readShort();
                                short msgId = str.readShort();
                                System.out.println(msgId);
                                int shortValue = str.readShort();
                                System.out.println(shortValue);
                                int intValue = str.readInt();
                                System.out.println(intValue);
                            }
                        });
                    }
                });
        try {
            ChannelFuture sync = serverBootstrap.bind(8000).sync();

            sync.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
            bossGroup.shutdownGracefully();
            workGroup.shutdownGracefully();
        }
    }
}
